'use strict';
let uniID = require('uni-id')
const createConfig = require('uni-config-center')
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	uniID = uniID.createInstance({
		context
	})

	const {
		uniIdToken,
		saveData
	} = event;

	if (!uniIdToken) {
		return {
			code: 403,
			msg: '缺少token'
		}
	}
	let payload = await uniID.checkToken(uniIdToken)
	if (payload.code && payload.code > 0) {
		return payload
	}
	const dayunix = new Date()
	const unix = dayunix.getTime()
	const saveInfo = JSON.parse(event.saveData)
	const uid = payload.uid
	console.log('UID=>',uid)
	const lastCache = await db.collection('test-history').where({
		user_id: uid
	}).limit(1).get()
	if (lastCache.data[0]) {
		const lastObj = lastCache.data[0]
		let update = {
			cacheType: saveInfo.cacheType,
			cachedata: JSON.stringify(saveInfo.cachedata),
			update_time: unix
		}

		console.log('update data=>', update)
		if (saveInfo.cacheType == "MOCKTEST") {
			update['role'] = saveInfo.role
		}
		
		const result = await db.collection('test-history').where({
			user_id: uid
		}).update(update)
		if (result) {
			return 'updateok'
		}
	} else {
		const addData = {
			cacheType: saveInfo.cacheType,
			cachedata:  JSON.stringify(saveInfo.cachedata),
			create_time: Date.now(),
			user_id: uid
		}
		if (saveInfo.cacheType == "MOCKTEST") {
			addData['role'] = saveInfo.role
		}
		const result = await db.collection('test-history').add(addData)
		if (result) {
			return result
		}
	}
};
